﻿namespace Blaze.Editor
{
    using System;
    using System.Reflection;
    using Dev;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// 开发命令管理器。
    /// </summary>
    public static class DevCommandManager
    {
        /// <summary>
        /// 快速执行指定的命令。
        /// </summary>
        /// <typeparam name="T">命令类型</typeparam>
        public static void Execute<T>() where T : DevCommand, new()
        {
            var cmd = new T();
            cmd.Execute();
        }

        /// <summary>
        /// 快速执行指定的命令。
        /// </summary>
        /// <param name="cmdType">命令类型</param>
        public static void Execute(Type cmdType)
        {
            if (cmdType == null || !typeof (DevCommand).IsAssignableFrom(cmdType))
                throw new ArgumentException("cmdType");
            var cmd = (DevCommand) Activator.CreateInstance(cmdType);
            cmd.Execute();
        }

        /// <summary>
        /// 记录一个命令的执行。
        /// </summary>
        /// <param name="command">命令</param>
        public static void Record(DevCommand command)
        {
            mLastCommand = command;
            PlayerPrefs.SetString(mLastCommandKey, command.GetType().FullName);
        }

        /// <summary>
        /// 重复上一次执行的命令。
        /// </summary>
        [MenuItem("Blaze/重复上一个命令 &R")]
        public static void RepeatLastCommand()
        {
            if (mLastCommand != null)
            {
                mLastCommand.Execute();
                return;
            }

            var lastCommandName = PlayerPrefs.GetString(mLastCommandKey, null);
            if (lastCommandName != null)
            {
                var cmdType = Assembly.GetExecutingAssembly().GetType(lastCommandName);
                Execute(cmdType);
            }
        }

        private const string mLastCommandKey = "DevCommandManager_LastCommand";

        private static DevCommand mLastCommand;
    }
}